public class VolatileDemo {
    volatile boolean stop = false;

    Runnable runnable = () -> {
        while (!stop) {
            //sth
        }
    };

    void start() {
        new Thread(runnable).start();
    }

    void stop() {
        this.stop = true;
    }

    public static void main(String[] args) throws Exception {
        VolatileDemo demo = new VolatileDemo();
        demo.start();

        Thread.sleep(1000);

        demo.stop();

    }
}
